import json, os, sys, subprocess, platform
import tkinter as tk

os.chdir(os.path.dirname(os.path.abspath(sys.argv[0])))
try:
    with open('page/config.json', 'r') as f:
        conf = json.load(f)
except FileNotFoundError:
    print('配置文件读取错误')
    exit(1)

def openfile(file):
    system = platform.system()
    file = os.getcwd() + '/' + file
    # 相对路径 -> 绝对路径
    if system == 'Windows':
        os.startfile(file)
        # subprocess.call(['start', file])
    elif system == 'Darwin':
        subprocess.call(['open', file])
    elif system == 'Linux':
        subprocess.call(['xdg-open', file])
    else:
        raise Exception('不支持的操作系统')

def blog_state_text(st):
    if st: return "关闭博客"
    else: return "开启博客"
def blog_change_state():
    conf["blog"]["state"] = not conf["blog"]["state"]
    blog_state_var.set(blog_state_text(conf["blog"]["state"]))
def blog_management():
    nw = tk.Toplevel(win)
    nw.title("Blog Management")
    nw.geometry("800x600")
    blog_state_var.set(blog_state_text(conf["blog"]["state"]))
    tk.Button(nw, textvariable = blog_state_var, command = blog_change_state).pack()
    tk.Button(nw, text = "编辑样式表", command = lambda: openfile('page/blog/style.css')).pack()
    tk.Button(nw, text = "编辑目录头部脚本", command = lambda: openfile('page/blog/head.js')).pack()
    tk.Button(nw, text = "编辑目录尾部脚本", command = lambda: openfile('page/blog/tail.js')).pack()
    tk.Button(nw, text = "编辑博客头部脚本", command = lambda: openfile('page/blog/head_blog.js')).pack()
    tk.Button(nw, text = "编辑博客尾部脚本", command = lambda: openfile('page/blog/tail_blog.js')).pack()

def save_setting():
    with open('page/config.json', 'w') as f:
        f.write(json.dumps(conf, indent = 4))

win = tk.Tk()
win.title("Cat Planet personal homepage FrameWork")
win.geometry("800x600")
blog_state_var = tk.StringVar()
tk.Button(win, text = "博客管理", command = blog_management).pack()
tk.Button(win, text = "保存设置", command = save_setting).pack()
win.mainloop()
